import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';

export async function GET(request: NextRequest) {
  try {
    // 获取查询参数
    const url = new URL(request.url);
    const keyword = url.searchParams.get('keyword') || '';
    const location = url.searchParams.get('location') || '';
    const jobType = url.searchParams.get('job_type') || '';
    const experience = url.searchParams.get('experience') || '';
    const education = url.searchParams.get('education') || '';
    const page = parseInt(url.searchParams.get('page') || '1');
    const limit = parseInt(url.searchParams.get('limit') || '10');

    // 计算偏移量
    const offset = (page - 1) * limit;

    // 构建查询条件
    let whereClause = 'WHERE jp.status = "active"';
    const queryParams: any[] = [];

    if (keyword) {
      whereClause += ' AND (jp.title LIKE ? OR jp.description LIKE ? OR jp.requirements LIKE ? OR c.name LIKE ?)';
      const likeParam = `%${keyword}%`;
      queryParams.push(likeParam, likeParam, likeParam, likeParam);
    }

    if (location) {
      whereClause += ' AND jp.location LIKE ?';
      queryParams.push(`%${location}%`);
    }

    if (jobType) {
      whereClause += ' AND jp.job_type = ?';
      queryParams.push(jobType);
    }

    if (experience) {
      whereClause += ' AND jp.experience = ?';
      queryParams.push(experience);
    }

    if (education) {
      whereClause += ' AND jp.education = ?';
      queryParams.push(education);
    }

    // 查询总数
    const [countResult] = await UserModel.query<any[]>(
      `SELECT COUNT(*) as total
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       ${whereClause}`,
      queryParams
    );

    const total = countResult[0]?.total || 0;

    // 查询职位列表 - 使用直接插入的方式构建SQL查询，避免参数化LIMIT和OFFSET
    const [jobs] = await UserModel.query<any[]>(
      `SELECT jp.id, jp.company_id, jp.title, jp.description, jp.requirements, jp.salary_range,
              jp.location, jp.job_type, jp.experience, jp.education, jp.status, jp.created_by,
              jp.application_count,
              DATE_FORMAT(jp.created_at, '%Y-%m-%d %H:%i:%s') as created_at,
              DATE_FORMAT(jp.updated_at, '%Y-%m-%d %H:%i:%s') as updated_at,
              c.name as company_name, c.logo as company_logo, c.industry as company_industry,
              c.size as company_size
       FROM job_positions jp
       LEFT JOIN companies c ON jp.company_id = c.id
       ${whereClause}
       ORDER BY jp.created_at DESC
       LIMIT ${limit} OFFSET ${offset}`,
      queryParams
    );

    // 返回结果
    return NextResponse.json({
      jobs,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('搜索招聘信息失败:', error);
    return NextResponse.json(
      { error: '搜索招聘信息失败' },
      { status: 500 }
    );
  }
}
